from django.utils.safestring import mark_safe
from django.urls import re_path
from django.shortcuts import HttpResponse, render, redirect
from stark.service.s1 import StarkHandler, choice_display, SearchOption
from rbac.models import UserInfo
from app_main.forms.for_stark import ResetPasswordForm, UserInfoAddModelForm, UserInfoEditModelForm


class UserInfoHandler(StarkHandler):
    search_col_list = ['name__contains', 'email__contains']
    search_group = [
        SearchOption('gender'),
        SearchOption('department', is_multi=True)
    ]

    def display_reset_pwd(self, obj=None, is_head=None):
        if is_head:
            return '重置密码'

        re_url = self.create_re_url('reset_password', obj.id)
        return mark_safe('<a href="%s">重置密码</a>' % re_url)

    list_display = [
        'name',
        'email',
        'phone',
        choice_display('性别', 'gender'),
        display_reset_pwd,
        StarkHandler.display_edit,
        StarkHandler.display_del
    ]

    def reset_pwd(self, request, nid):  # 用户重置密码执行的视图函数
        obj = UserInfo.objects.filter(id=nid).first()
        if not obj:
            return HttpResponse('用户不存在')

        if request.method == 'GET':
            my_form = ResetPasswordForm()
            return render(request, 'stark/change.html', {'my_form': my_form})

        if request.method == 'POST':
            my_form = ResetPasswordForm(data=request.POST)
            if my_form.is_valid():
                pwd = my_form.cleaned_data['password']
                obj.password = pwd
                obj.save()
                return redirect(self.back_list_url())
            else:
                return render(request, 'stark/change.html', {'my_form': my_form})

    def extra_urls(self):
        patterns = [
            re_path('reset/password/(?P<nid>\d+)/$', self.wrapper(self.reset_pwd), name=self.get_url_name('reset_password'))
        ]

        return patterns

    def get_model_form_class(self, add_or_edit, request, *args, **kwargs):
        if add_or_edit == 'add':
            return UserInfoAddModelForm
        elif add_or_edit == 'edit':
            return UserInfoEditModelForm
